package com.fecean.aabbc.netty.client.prod7;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * Netty客户端定时任务，用于启动连接服务端
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2020-03-05 16:57
 * @blame Team
 */
@Slf4j
@Component
public class NettyClientTimerTask implements TimerTask {

    /**
     ** Netty客户端启动
     */
    @Autowired
    NettyClientStarter nettyClientStarter;

    /**
     ** Netty客户端引导
     */
    @Autowired
    Bootstrap bootstrap;

    /**
     ** 影院配置
     */
    @Resource
    CinemaConfig cinemaConfig;

    /**
     ** 定时任务运行方法体
     *
     * @param timeout 超时设置
     */
    @Override
    public void run(Timeout timeout) {
        run();
    }

    /**
     ** Netty客户端运行
     */
    public void run(){
        log.info("客户端[{}-{}]进行连接服务端[{}:{}]", cinemaConfig.getTenantId(),
                cinemaConfig.getCinemaCode(), "127.0.0.1", 8090);
        synchronized (bootstrap) {
            try {
                // 进行连接服务端
                ChannelFuture future = bootstrap.connect("127.0.0.1", 8090).sync();
                // 异步等待关闭
                future.channel().closeFuture().sync();
            } catch (Exception e) {
                log.error("客户端[{}-{}]连接报错，可能是服务端未启动或网络异常",
                        cinemaConfig.getTenantId(), cinemaConfig.getCinemaCode());
                log.error("", e);
                // 连接异常后，将进行重新连接
                nettyClientStarter.reconnect();
            }
        }
    }
}
